﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TianYu.CMS.Domain.DomainModel;
using TianYu.CMS.Domain.ViewModel.Request;
using TianYu.CMS.Infrastructure.Enums;
using TianYu.CMS.Service;
using TianYu.Core.Common;
using TianYu.Core.DataBase;

namespace TianYu.CMS.WebMvc.Areas.Admin.Controllers
{
    public class ArticleCategoryController : BaseController
    {
        private IArticleCategoryService _articleCategoryService;
        public ArticleCategoryController(IArticleCategoryService articleCategoryService)
        {
            this._articleCategoryService = articleCategoryService;
        }


        public IActionResult Index()
        {
            return View();
        }
        public IActionResult AddEdit(int? id, int? pid, int? level)
        {
            var model = new ArticleCategory()
            {
                Id = id.HasValue ? id.Value : -1,
                ParentId = pid.HasValue ? pid.Value : -1,
                Level = level.HasValue ? level.Value : 1,
                Status = 0
            };

            var list = _articleCategoryService.Query(o => o.Status == StatusEnum.Effective).ToList();

            var menu = new ArticleCategory()
            {
                Id = -1,
                Name = "顶级",
                Level = 1,
                ParentId = -1,
                Sort = -1
            };
            list.Add(menu);
            var items = list.Select(t => new { id = t.Id, name = t.Name, pId = t.ParentId, open = t.ParentId == -1 });
            ViewBag.TreeJson = items.ToJsonString();

            if (id.HasValue && id > 0)
            {
                model = _articleCategoryService.FindSingle(o => o.Id == id);
            }
            ViewBag.ParentName = list.FirstOrDefault(t => t.Id == model.ParentId).Name;
            return View(model);
        }




        public async Task<AjaxResult<IEnumerable<ArticleCategory>>> GetList([FromQuery] ArticleCategoryListRequestModel requestModel)
        {
            var filter = Expressionable.Create<ArticleCategory>()
                .And(o => o.Status == (int)StatusEnum.Effective)
                .AndIF(!requestModel.KeyWords.IsNullOrWhiteSpace(), o => o.Name.Contains(requestModel.KeyWords))
                .ToExpression();

            var list = await _articleCategoryService.QueryAsync(filter, o => o.Sort, OrderByType.Asc);

            var res = new AjaxResult<IEnumerable<ArticleCategory>>();
            res.Data = list;

            return res;
        }
        public async Task<AjaxResult<bool>> Save(SaveArticleCategoryRequestModel requestModel)
        {
            if (requestModel.Id > 0)
            {
                if (requestModel.Name.IsNullOrWhiteSpace())
                {
                    return AjaxResult<bool>.Fail("分类名称不能为空");
                }

                if (_articleCategoryService.Count(o => o.Id != requestModel.Id && o.Name == requestModel.Name && o.Status == 0 && o.ParentId == requestModel.ParentId) > 0)
                {
                    return AjaxResult<bool>.Fail($"分类名称[{requestModel.Name}]已存在，不能重复添加");
                }
            }

            var model = requestModel.MapTo<ArticleCategory>();

            if (requestModel.Id > 0)
            {
                await _articleCategoryService.UpdateAsync(o => new ArticleCategory()
                {
                    Name = model.Name,
                    ParentId = model.ParentId,
                    Sort = model.Sort,
                    Level = model.Level,
                    Modifier = LoginUserName,
                    ModifyGuid = LoginUserGuid,
                    ModifyTime = DateTime.Now
                }, x => x.Id == model.Id);
            }
            else
            {
                model.CreateGuid = base.LoginUserGuid;
                model.CreateTime = DateTime.Now;
                model.Creator = base.LoginUserName;

                await _articleCategoryService.InsertAsync(model);
            }
            return AjaxResult<bool>.Success();
        }
        public async Task<AjaxResult<bool>> Remove(int[] ids)
        {
            bool result = await _articleCategoryService.UpdateAsync(o => new ArticleCategory()
            {
                Status = Infrastructure.Enums.StatusEnum.Invalid,
                Modifier = LoginUserName,
                ModifyGuid = LoginUserGuid,
                ModifyTime = DateTime.Now
            }, o => ids.Contains(o.Id));

            return result ? AjaxResult<bool>.Success() : AjaxResult<bool>.Fail("删除失败");
        }
    }
}